/**
 * 
 */
package com.heer.RD.projecthour.page;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.wicket.PageParameters;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.OnChangeAjaxBehavior;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.ajax.markup.html.form.AjaxSubmitButton;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.HiddenField;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.link.ExternalLink;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.util.value.ValueMap;
import org.apache.wicket.validation.validator.StringValidator;

import com.heer.RD.projecthour.component.DeptChoice;
import com.heer.RD.projecthour.component.DeptProjChoice;
import com.heer.RD.projecthour.component.ProjChoice;
import com.heer.RD.projecthour.pojo.ProjectDTO;
import com.heer.RD.projecthour.pojo.UserHourDTO;
import com.heer.RD.util.UtilsMisc;



/**
 * @author ZhaoZehui
 *
 */
public class MainPage extends BasePage {

	/**
	 * 
	 */
	public MainPage(PageParameters para) {
		
		String currDateStr = para.getString("d");
		
		if(StringUtils.isBlank(currDateStr) || !UtilsMisc.isDate(currDateStr)) {
			currDateStr = UtilsMisc.getCurrDateStr();
		}
		final FeedbackPanel feedbackPanel = new FeedbackPanel("feedback");
		feedbackPanel.setOutputMarkupId(true).setMarkupId("feedbackPanel");
	
		final DeptProjChoice allProjs = new DeptProjChoice("allprojs", 6);
		allProjs.setMarkupId("allprojs");
		allProjs.setOutputMarkupId(true);
		allProjs.init(getMainService().getDeptAndProjs(getUser(), true));
		
		final DeptChoice depts = new DeptChoice("depts", getMainService().getJdbcTemplate(), "root");
		depts.setOutputMarkupId(true);
		final ProjChoice projs = new ProjChoice("projs");
		projs.setOutputMarkupId(true);
		
		//首先查这个日期有没有登记过工时
		//然后和本部门的所有其他项目去除重复项目合并
		final List<Map> projStoreList = getMainService().getJdbcTemplate().queryForList("select u.user_hour_id,u.project_id,u.hour_cost,u.reg_memo,p.proj_name,p.begin_date,p.task_addr,p.is_end,p.budget_hour,p.curr_milestone,p.pm,p.dept_id,d.dept_name,p.father_proid from user_hour u,project p,department d where u.project_id = p.project_id and p.dept_id = d.dept_id and u.user_id = '"+getUser().getUserId()+"' and u.reg_date = '"+currDateStr+"' order by p.dept_id,p.begin_date desc");
//		List<ProjectDTO> pList = getMainService().getProjDao().queryByCriteria("dept_id in ('"+StringUtils.join(DeptChoice.getLevel1AndSubDepts(getMainService().getJdbcTemplate(), getUser().getDeptId()), "','")+"') and project_id not in (select project_id from user_hour where user_id = '"+getUser().getUserId()+"' and reg_date = '"+currDateStr+"') order by dept_id,begin_date desc");
//		for (ProjectDTO p : pList) {
//			Map regMap = regProj(p.getProjectId(), regProjHourList);
//			if(regMap == null) {
//				addEmptyProj(projStoreList, p, depts);
//			}
//			else {
//				projStoreList.add(regMap);
//			}
//		}
		
		//对projStoreList排序，按照项目->子项目/任务的方式排序
		
		
		
		final HiddenField regDate = new HiddenField("selectedDateInput", new Model<String>(currDateStr));
		regDate.setMarkupId("selectedDateInput").setOutputMarkupId(true);

		final Form f = new Form("thisForm", new CompoundPropertyModel(new ValueMap())) {
			protected void onSubmit() {
				final ValueMap values = (ValueMap)getModelObject();
				if(check(projStoreList)) {
					
					//删除所有
					getMainService().getUserHourDao().removeByCriteria("user_id = '"+getUser().getUserId()+"' and reg_date = '"+regDate.getModelObject().toString()+"'");
					
					for (Map<String,String> map : projStoreList) {
						//没有录入工时的不记录
						if(Double.parseDouble(map.get("HOUR_COST")) > 0) {
							UserHourDTO uh = new UserHourDTO();
							uh.setProjectId(map.get("PROJECT_ID"));
							uh.setUserId(getUser().getUserId());
							uh.setRegMemo(map.get("REG_MEMO"));
							uh.setHourCost(Double.parseDouble(map.get("HOUR_COST")));
							uh.setRegDate(regDate.getModelObject().toString());
							uh.setUpdateDate(UtilsMisc.getCurrTimeStr());
							getMainService().getUserHourDao().create(uh);
						}
					}
					info("提交成功");
				}
				else {
					error("出错提示：1、录入工时不能为空，且请输入数字，大于0的才会被记录；2、如果登记了工时，请填写工作记录和备注");
				}
				
			}
		};

		f.add(feedbackPanel);
		
		f.add(new Label("selectedDate", currDateStr));
		f.add(regDate);
		
		final WebMarkupContainer projListPanel = new WebMarkupContainer("projListPanel");
		projListPanel.setOutputMarkupId(true);
		
		projListPanel.add(new ListView("projList", projStoreList) {
			protected void populateItem(ListItem item) {
				
				final Map row = (Map)item.getModel().getObject();

				item.add(new Label("beginDate", new PropertyModel(item.getModel(), "BEGIN_DATE")));
				item.add(new RequiredTextField("userHour", new PropertyModel(item.getModel(), "HOUR_COST")).setMarkupId("userHour").setOutputMarkupId(true));
				item.add(new TextArea("hourMemo", new PropertyModel(item.getModel(), "REG_MEMO"))
						.add(StringValidator.maximumLength(500))
						);
				
				Label projIdx = new Label("projectIdx", (item.getIndex()+1)+"");
				item.add(projIdx);
				Label mileLabel = new Label("milestone", new Model<String>((row.get("CURR_MILESTONE")==null?"":row.get("CURR_MILESTONE"))+"阶段"));
				item.add(mileLabel);
				Label deptLabel = new Label("dept", new PropertyModel(item.getModel(), "DEPT_NAME"));
				item.add(deptLabel);
				
				if(StringUtils.isEmpty((String)row.get("FATHER_PROID"))) {
					item.add(new ExternalLink("projectName", new PropertyModel(item.getModel(), "TASK_ADDR"), new PropertyModel(item.getModel(), "PROJ_NAME")));
				}
				else {
					item.add(new ExternalLink("projectName", null, "[子项目]"+row.get("PROJ_NAME")));
					deptLabel.setDefaultModel(new Model<String>("属于["+getMainService().getProjName((String)row.get("FATHER_PROID"))+"]"));
					
					mileLabel.setVisible(false);
				}
				
				item.add(new AjaxLink("delLink") {

					@Override
					public void onClick(AjaxRequestTarget target) {
						projStoreList.remove(row);
						target.addComponent(projListPanel);
					}

				});
				
			}
			
		});
		f.add(projListPanel);
		
		add(f);
		
		
		final Form appendProjForm = new Form("appendProjForm", new CompoundPropertyModel(new ValueMap())) {
			protected void onSubmit() {
			}
		};
		
		appendProjForm.add(new AjaxSubmitButton("appendProjButt") {

			@Override
			protected void onSubmit(AjaxRequestTarget target, Form form) {
				String projId = allProjs.getModelValue();
				
				if(StringUtils.isNotBlank(projId) && !"-1".equals(projId) && !projId.startsWith("dept")) {
					
					projId = projId.substring(1);
					
					Map regMap = regProj(projId, projStoreList);
					if(regMap == null) {
						ProjectDTO p = getMainService().getProjById(projId);
						addEmptyProj(projStoreList, p, depts);
						f.info("["+p.getProjName()+"] 增加成功");
					}
					else {
						f.error("该项目已存在");
					}
				}
				else {
					f.error("请双击项目名称增加");
				}
				target.addComponent(projListPanel);
				target.addComponent(f);
			}
			
		}.setMarkupId("appendProjButt").setOutputMarkupId(true));
		
		appendProjForm.add(allProjs);
		add(appendProjForm);
		
		
		final Form addProjForm = new Form("addProjForm", new CompoundPropertyModel(new ValueMap())) {
			protected void onSubmit() {
			}
		};
		
		OnChangeAjaxBehavior changeDept = new OnChangeAjaxBehavior() {
			protected void onUpdate(AjaxRequestTarget target) {
				String deptId = depts.getModelValue();
				projs.getProjByDept(getMainService().getJdbcTemplate(), deptId);
				target.addComponent(projs);
			}
			
		};
		
		addProjForm.add(new AjaxSubmitButton("addProjButt") {

			@Override
			protected void onSubmit(AjaxRequestTarget target, Form form) {
				String projId = projs.getModelValue();
				if(StringUtils.isNotBlank(projId) && !"-1".equals(projId)) {
					Map regMap = regProj(projId, projStoreList);
					if(regMap == null) {
						ProjectDTO p = getMainService().getProjById(projId);
						addEmptyProj(projStoreList, p, depts);
						f.info("添加成功，工时为0不会被记录");
					}
					else {
						f.error("该项目已存在");
					}
				}
				else {
					f.error("请选择项目后增加");
				}
				target.addComponent(projListPanel);
				target.addComponent(f);
			}
			
		});
		
        depts.add(changeDept);
        addProjForm.add(depts);
        addProjForm.add(projs);
        
		add(addProjForm);
		
		//把从其他大部门引入项目的功能暂时屏蔽掉，目前没有什么用
		addProjForm.setVisible(false);
		
	}
	
	
	private boolean check(List<Map> projStoreList) {
		for (Map map : projStoreList) {
			if(StringUtils.isBlank((String)map.get("HOUR_COST"))) 
				return false;
			try {
				Double userHour = Double.parseDouble((String)map.get("HOUR_COST"));
				
				if(userHour > 0 && StringUtils.isBlank((String)map.get("REG_MEMO"))) {
					return false;
				}
				
			} catch (NumberFormatException e) {
				return false;
			}
		}
		return true;	
	}
	
	private Map regProj(String pid, List<Map> regProjHourList) {
		for (Map map : regProjHourList) {
			if(pid.equals(map.get("PROJECT_ID"))) {
				return map;
			}
		}
		return null;
	}
	
	private void addEmptyProj(List<Map> projStoreList, ProjectDTO p, DeptChoice depts) {
		projStoreList.add(UtilsMisc.toMap(
				"USER_HOUR_ID","",
				"PROJECT_ID",p.getProjectId(),
				"PROJ_NAME",p.getProjName(),
				"TASK_ADDR",p.getTaskAddr(),
				"IS_END",p.getIsEnd(),
				"BEGIN_DATE",p.getBeginDate(),
				"CURR_MILESTONE",p.getCurrMilestone(),
				"HOUR_COST",new Double("0.0"),
				"REG_MEMO","",
				"DEPT_NAME",depts.getDeptName(p.getDeptId()),
				"FATHER_PROID",p.getFatherProid()
				));
	}
}
